/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package de.jrk_verwaltung.security.login;

import java.util.Iterator;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;

import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.log4j.Logger;

import de.jrk_verwaltung.security.login.stats.CFailureInactiveState;
import de.jrk_verwaltung.security.login.stats.CFailureState;
import de.jrk_verwaltung.security.login.stats.CNotLogOnState;
import de.jrk_verwaltung.security.login.stats.CSuccesState;
import de.jrk_verwaltung.security.login.stats.ILoginState;
import de.jrk_verwaltung.security.user.CUser;

/**
 * 
 * @author JRK-FO
 */
public final class CLoginModel {

    private static final Logger logger = Logger.getLogger(CLoginModel.class);
    private EntityManager entityManager;
    private final EntityManagerFactory emf;

    public CLoginModel(EntityManagerFactory emf) {
        this.emf = emf;

    }

    public ILoginState login(final String userName, final String password) {
        ILoginState loginState = new CNotLogOnState();
        try {
            this.entityManager = emf.createEntityManager();
            final String userSQL = " SELECT u from CUser u where u.username = :userName and u.password = :password";
            final Query userQuery = entityManager.createQuery(userSQL);
            userQuery.setParameter("userName", userName);
            userQuery.setParameter("password", password);
            @SuppressWarnings("unchecked")
            final List<CUser> userList = userQuery.getResultList();
            if (!userList.isEmpty()) {
                if (userList.size() == 1) {
                    Iterator<CUser> userListItems = userList.iterator();
                    if (userListItems.next().getActiv()) {
                        loginState = (new CSuccesState());
                    } else {
                        loginState = (new CFailureInactiveState());
                    }
                }
            } else {
                loginState = (new CFailureState());
            }
            entityManager.close();
            return loginState;

        } catch (IllegalStateException ex) {
            logger.fatal(ex);
            loginState = (new CNotLogOnState());
            return loginState;
        }
    }

    @Override
    public boolean equals(Object obj) {
        CLoginModel loginModel;
        if (obj instanceof CLoginModel) {
            loginModel = (CLoginModel) obj;
        } else {
            return false;
        }
        if (this != loginModel) {
            return false;
        }
        return true;
    }

    @Override
    public int hashCode() {
        return new HashCodeBuilder().toHashCode();
    }
}
